import { BadRequestException, Injectable } from '@nestjs/common'
import { InjectModel } from '@nestjs/mongoose'
import { WxUser, UserDocument } from '@libs/db/schemas/user.schema'
import { JwtService } from '@nestjs/jwt'
import { Model } from 'mongoose'
import { UserLogin } from './dto'
import { compareSync } from 'bcryptjs'

@Injectable()
export class AuthService {
  constructor(
    private readonly jwtService: JwtService,
    @InjectModel(WxUser.name) private UserModel: Model<UserDocument>
  ) {}

  async userLogin(userDto: UserLogin): Promise<any> {
    // return await this.UserModel.create(userDto);
    const { username, password } = userDto
    const user = await this.UserModel.findOne({ username }).select('+password')
    if (!user) {
      throw new BadRequestException('用户名不正确')
    }
    if (!compareSync(password, user.password)) {
      throw new BadRequestException('密码不正确')
    }
    // 返回值会挂载到 controller层 @Request() req.user
    const token = this.jwtService.sign({ username, id: user._id })
    // console.log(
    //   'jwtService',
    //   this.jwtService.verify(token, { secret: config.server.scret }),
    // );
    return { token }
  }

  async loginJwt(id: string): Promise<any> {
    const _id = id
    return {
      token: this.jwtService.sign(_id),
    }
  }

  async getUserInfo(id: string) {
    return this.UserModel.findById(id).exec()
  }
}
